import { Tag } from '@prisma/client';
import { TX } from '../db';
import { TagDomain } from '~/common/tag-domain';

function tagService(domain: number) {
  return {
    async create(tx: TX, name: string): Promise<Tag> {
      if (!name) {
        throw new Error('Invalid tag name');
      }
      // TODO: 创建已删除的标签应处理

      return tx.tag.create({
        data: {
          name,
          domain,
          createTime: new Date(),
          deleteTime: null,
        },
      });
    },
    async findByIds(tx: TX, ids: bigint[]): Promise<Tag[]> {
      if (ids.length === 0) {
        return [];
      }

      return tx.tag.findMany({
        where: {
          id: { in: ids },
          domain,
          deleteTime: null,
        },
      });
    },
    async search(tx: TX, prefix: string, limit: number): Promise<Tag[]> {
      if (!prefix) {
        return [];
      }

      return tx.tag.findMany({
        where: {
          name: { startsWith: prefix },
          domain,
          deleteTime: null,
        },
        take: limit,
      });
    },
  };
}

export const postTagService = tagService(TagDomain.POST);
